<template>
    <div class="today-work-hour-chart">
        <div
            class="timeline-chart"
            id="timeline"
            ref="timeline"> </div>
    </div>
</template>

<script>
import _ from 'lodash';
import * as echart from 'echarts';
import moment from 'moment';
import { apiService } from '@/api/apiService.js';
import { preLoadPerdeviceParamValue } from '@/api/server';
import timeLinePieOption from '../options/timeLinePieOption';

let TimelineChart = null;
export default {
    props: {
        uuid: String
    },
    data () {
        return {
            timeline: {},
            device_param_data: [],
            chartData: [],
            color: {
                Running: '#4dca72',
                Idle: '#fcda55',
                Estop: '#f2637b',
                Offline: '#cccccc',
                remaining_time: '#ddf'
            }
        };
    },
    watch: {
        timeline (res) {
            this.setChartSeries(TimelineChart);
        }
    },
    activated () {
        console.log('激活了');
        this.device_data_refresh = setInterval(() => {
            this.getDeviceParams();
        }, 60000);
        this.getDeviceParams();
        this.$nextTick(() => {
            const el = this.$refs.timeline;
            this.initChart(el);
            this.setChartSeries(TimelineChart);
        });
    },
    deactivated () {
        clearInterval(this.device_data_refresh);
        if (TimelineChart) {
            TimelineChart.dispose();
            TimelineChart = null;
        }
    },
    computed: {
        timelinedata () {
            if (!this.timeline) {
                return [];
            }
            let times = '';
            if (this.timeline.value) {
                times = this.timeline.value.filter((time) => {
                    return moment(time._timeStamp) >= moment().startOf('day');
                });
            }
            // this.timeline.value = times;
            // let timelinedata = this.device_param_data.find((child) => {
            //     return child.status === 'WHstatus_Timeline';
            // });

            if (!times) {
                return [];
            }

            // if (timelinedata) {
            //     timelinedata = {
            //         ...timelinedata,
            //         time: timelinedata._timeStamp
            //     };
            // }
            return times ? this.getTimelineData({
                status: this.timeline.status,
                value: times,
                time: this.timeline.tz
            }) : [];
        }
    },
    methods: {
        initChart (el) {
            if (TimelineChart !== null && TimelineChart !== undefined) {
                TimelineChart.clear();
            }

            TimelineChart = echart.init(el);

            TimelineChart.clear();
            // 设置配置信息,并初始化chart
            this.$nextTick(() => {
                TimelineChart.setOption(timeLinePieOption(this.chartData));
            });
        },
        getDeviceParams () {
            // TODO 调用后端方法: 获取设备的使用情况
            if (this.uuid) {
                apiService({
                    api: preLoadPerdeviceParamValue,
                    param: {
                        uuid: this.uuid
                    },
                    success: (data) => {
                        this.timeline = data.status_snapshot.find((child) => {
                            return child.status === 'WHstatus_Timeline';
                        });
                    }
                });
            } else {
                this.timeline = {};
            }
        },
        toDayDate: function () {
            const year = new Date().getFullYear();
            const month = new Date().getMonth() + 1;
            const day = new Date().getDate();
            const date = new Date(year + '/' + month + '/' + day);
            return date;
        },
        newdate: function (str) {
            const time = new Date(str).getTime();
            if (!Number.isNaN(time)) {
                return new Date(str);
            } else if (typeof str === 'string') {
                const time1 = str.replace(/-/g, '/');
                const time2 = time1.split('.')[0];
                let ms = time1.split('.')[1];
                if (ms && ms.length > 3) {
                    ms = ms.substring(0, 3);
                }
                const time = new Date(time2).getTime() + Number.parseFloat(ms);
                return new Date(time);
            }
            return new Date();
        },
        getTimelineData (timeline) {
            const g_timeline = _.cloneDeep(timeline);
            var newObj = {
                value: []
            };
            let today = this.toDayDate();
            const morning = today;
            if (this.newdate(g_timeline.time) <= morning) {
                // 凌晨
                today = today.toISOString();
                // 然后转化为东八区，当前的时间;
                var currents = new Date().toISOString();
                const obj1 = {
                    _timeStamp: today,
                    _value: 'Offline'
                };
                const obj2 = {
                    _timeStamp: currents,
                    _value: ''
                };
                g_timeline.value = [];
                g_timeline.value.push(obj2);
                g_timeline.value.push(obj1);
            } else {
                // 把当前的时间戳压进去,
                const currents = new Date().toISOString();
                var b = {
                    _timeStamp: currents,
                    _value: ''
                };
                g_timeline.value.push(b);
            }

            var compare = (obj1, Obj2) => {
                var val1 = this.newdate(obj1._timeStamp).getTime();
                var val2 = this.newdate(Obj2._timeStamp).getTime();
                if (val1 < val2) {
                    return -1;
                } else if (val1 > val2) {
                    return 1;
                }
                return 0;
            };

            g_timeline.value.sort(compare);
            // 判断是否在同一天
            // var data1 = g_timeline.value[0]._timeStamp.substring(0, 10);
            // var data2 = g_timeline.value[
            //   g_timeline.value.length - 1
            // ]._timeStamp.substring(0, 10);
            // 让不在一天以内的时间，统一到在一天以内，删除那些不在一天以内的元素；
            var time_diff1, time_diff2;
            // 把数组的时间差放进数组对象里；
            for (var i = 0; i < g_timeline.value.length - 1; i++) {
                var _1 = g_timeline.value[i];
                var _2 = g_timeline.value[i + 1];
                time_diff1 = this.newdate(_1._timeStamp).getTime() / 1000;
                // 获取数组的第一个时间的毫秒数；
                // 第一个数据
                var obj0 = this.newdate(g_timeline.value[0]._timeStamp).getTime() / 1000;
                time_diff2 = this.newdate(_2._timeStamp).getTime() / 1000;
                var obj2 = {
                    _timeStamp: time_diff2 - time_diff1,
                    _value: _1._value,
                    time: time_diff1 - obj0
                };
                newObj.value.push(obj2);
            }
            // 动态生成=============================
            return newObj.value;
        },
        setChartSeries (chart) {
            const timeline_length = this.timelinedata.length;
            const timeline = _.cloneDeep(this.timelinedata);
            if (timeline[timeline_length - 1] && timeline[timeline_length - 1]._value === '') {
                timeline[timeline_length - 1]._value = 'remaining_time';
                timeline[timeline_length - 1]._timeStamp = 24 * 60 * 60 - timeline[timeline_length - 1].time;
            } else if (timeline[timeline_length - 1]) {
                timeline[timeline_length] = {};
                timeline[timeline_length]._value = 'remaining_time';
                timeline[timeline_length]._timeStamp = 24 * 60 * 60 - timeline[timeline_length - 1].time - timeline[timeline_length - 1]._timeStamp;
                timeline[timeline_length].time = timeline[timeline_length - 1].time + timeline[timeline_length - 1]._timeStamp + 1;
            }
            this.InitTimelineData(timeline);
            // chart.clear();
            this.$nextTick(() => {
                chart.clear();
                chart.setOption(timeLinePieOption(this.chartData));
            });
        },
        getTimeBySecond (value) {
            let hour = Math.floor(value / (60 * 60));
            let minute = Math.floor((value % (60 * 60)) / 60);
            let second = Math.floor((value % (60 * 60)) % 60);

            hour = this.getFull(hour);
            minute = this.getFull(minute);
            second = this.getFull(second);

            return (this.precision === 'min' || hour === '24' || hour === '00') ? (hour + ':' + minute) : (hour + ':' + minute + ':' + second);
        },
        getFull (num) {
            return num >= 10 ? num : '0' + num;
        },
        InitTimelineData (timeline) {
            this.chartData = [];
            for (let i = 0; i < timeline.length; i++) {
                this.chartData.push({
                    value: timeline[i]._timeStamp,
                    name: `${this.$t(timeline[i]._value.toLowerCase())}`,
                    itemStyle: { color: this.color[timeline[i]._value] || '#fff' },
                    starttime: timeline[i].time,
                    endtime: timeline[i].time + timeline[i]._timeStamp,
                    tooltip: {
                        position: 'top',
                        formatter: (params) => {
                            console.log(params);
                            return `${params.marker} ${params.name}：${this.getTimeBySecond(params.data.starttime)}-${params.name !== this.$t('remaining_time') ? this.getTimeBySecond(params.data.endtime) : '24:00:00'}`;
                        }
                    }
                });
            }
        }
    }
};
</script>

<style lang="scss" scoped>
.today-work-hour-chart{
    .timeline-chart {
        // margin-left:%;
        width: 95%;
        height: 220px;
    }
}
</style>
